﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// 字节转换助手
/// </summary>
public static class ByteConvertHelper 
{
	/// <summary>
	/// 结构体到字节集
	/// </summary>
	/// <returns>数据</returns>
	/// <param name="origin">结构体</param>
	public static byte[] StructToBytes(object structure)
	{
		byte[] buff = new byte[Marshal.SizeOf(structure)];
		IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
		Marshal.StructureToPtr(structure, ptr, true);
		return buff;
	}

	/// <summary>
	/// 字节集到结构体
	/// </summary>
	/// <returns>结构体</returns>
	/// <param name="buff">数据</param>
	/// <param name="type">结构体类型</param>
	public static object BytesToStruct(byte[] buff, Type type)
	{
		IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
		return Marshal.PtrToStructure(ptr, type);
	}

	/// <summary>
	/// 对象到字节集
	/// </summary>
	/// <returns>数据</returns>
	/// <param name="origin">序列化对象</param>
	public static byte[] ObjectToBytes(object serializable)
	{
		byte[] buff;
		using (MemoryStream memoryStream = new MemoryStream())
		{
			IFormatter iFormatter = new BinaryFormatter();
			iFormatter.Serialize(memoryStream, serializable);
			buff = memoryStream.GetBuffer();
		}
		return buff;
	}

	/// <summary>
	/// 字节集到对象
	/// </summary>
	/// <returns>对象</returns>
	/// <param name="buff">数据</param>
	public static object BytesToObject(byte[] buff)
	{
		object serializable;
		using (MemoryStream memoryStream = new MemoryStream(buff))
		{
			IFormatter iFormatter = new BinaryFormatter();
			serializable = iFormatter.Deserialize(memoryStream);
		}
		return serializable;
	}
}
